<template>
  <view class="address-page">
    <!-- 状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>

    <!-- 自定义导航栏 -->
    <view class="custom-nav-bar" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="nav-back" @click="goBack">
        <uni-icons type="left" size="20" color="#333333"></uni-icons>
      </view>
      <view class="nav-title">收货地址</view>
    </view>

    <!-- 内容区域 -->
    <scroll-view class="content-scroll" scroll-y>
      <!-- 地址列表 -->
      <view class="address-list">
        <view v-for="(item, index) in addressList" :key="index" class="address-item">
          <view class="address-content" @click="selectAddress(item)">
            <view class="address-header">
              <text class="address-name">{{ item.name }}</text>
              <text class="address-tel">{{ item.tel }}</text>
            </view>
            <view class="address-detail">{{ item.address }}{{ item.desc }}</view>
          </view>
          <view class="address-actions">
            <view class="action-btn" @click.stop="editAddress(item)">
              <uni-icons type="compose" size="18" color="#ff0000"></uni-icons>
            </view>
            <view class="action-btn" @click.stop="deleteAddress(item)">
              <uni-icons type="close" size="18" color="#ff0000"></uni-icons>
            </view>
          </view>
        </view>
      </view>

      <!-- 无数据提示 -->
      <view v-if="addressList.length === 0 && !loading" class="no-address">
        <text>暂无收货地址</text>
      </view>
    </scroll-view>

    <!-- 底部新增按钮 -->
    <view class="add-btn" @click="addAddress">
      <uni-icons type="plus" size="20" color="#ffffff"></uni-icons>
      <text class="add-btn-text">新增地址</text>
    </view>
  </view>
</template>

<script>
import { addressApi } from '@/api/indexAPI.js';

export default {
  data() {
    return {
      statusBarHeight: 0,
      addressList: [],
      loading: false
    };
  },
  onLoad() {
    this.getStatusBarHeight();
    this.loadAddressList();
  },
  onShow() {
    // 页面显示时刷新地址列表（从编辑页面返回时）
    this.loadAddressList();
  },
  methods: {
    // 获取状态栏高度
    getStatusBarHeight() {
      try {
        const systemInfo = uni.getSystemInfoSync();
        this.statusBarHeight = systemInfo.statusBarHeight || 0;
      } catch (err) {
        console.error('获取状态栏高度失败', err);
        this.statusBarHeight = 20;
      }
    },
    // 返回
    goBack() {
      uni.navigateBack();
    },
    // 加载地址列表
    async loadAddressList() {
      this.loading = true;
      try {
        const res = await addressApi.getAddressList();
        console.log("获取地址列表:", res);

        if (res.code === 1 && res.data) {
          this.addressList = Array.isArray(res.data) ? res.data : [];
        } else {
          console.log("获取地址列表失败:", res.msg || res.message);
          this.addressList = [];
        }
      } catch (error) {
        console.error("获取地址列表异常:", error);
        this.addressList = [];
        uni.showToast({
          title: '获取地址列表失败',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    // 选择地址（如果是从其他页面跳转过来选择地址）
    selectAddress(item) {
      // 向打开本页的页面回传所选地址
      try {
        const pages = getCurrentPages();
        const currPage = pages[pages.length - 1];
        const eventChannel = currPage.getOpenerEventChannel && currPage.getOpenerEventChannel();
        if (eventChannel) {
          eventChannel.emit('addressSelected', item);
        }
      } catch (e) {
        console.error('回传地址失败', e);
      }
      uni.navigateBack();
    },
     // 新增地址
     addAddress() {
       uni.navigateTo({
         url: '/pages/location/add'
       });
     },
    // 编辑地址
    editAddress(item) {
      uni.navigateTo({
        url: `/pages/location/add?id=${item.id}`
      });
    },
    // 删除地址
    deleteAddress(item) {
      uni.showModal({
        title: '提示',
        content: '确定要删除该收货地址吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              const result = await addressApi.deleteAddress(item.id);
              console.log("删除地址结果:", result);

              if (result.code === 1) {
                uni.showToast({
                  title: '删除成功',
                  icon: 'success'
                });
                // 刷新地址列表
                this.loadAddressList();
              } else {
                uni.showToast({
                  title: result.msg || '删除失败',
                  icon: 'none'
                });
              }
            } catch (error) {
              console.error("删除地址异常:", error);
              uni.showToast({
                title: '删除失败',
                icon: 'none'
              });
            }
          }
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.address-page {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 状态栏占位 */
.status-bar {
  width: 100%;
  background-color: #ffffff;
}

/* 自定义导航栏 */
.custom-nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  background-color: #ffffff;
  border-bottom: 1px solid #f0f0f0;
}

.nav-back {
  position: absolute;
  left: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 44px;
  height: 44px;
  z-index: 1001;
}

.nav-title {
  font-size: 18px;
  font-weight: 700;
  color: #333333;
}

/* 内容区域 */
.content-scroll {
  height: calc(100vh - 44px - 60px);
  margin-top: 44px;
  padding-bottom: 60px;
}

.address-item {
  display: flex;
  align-items: center;
  background-color: #ffffff;
  padding: 30rpx 20rpx;
  margin-bottom: 1px;
}

.address-item:first-child {
  margin-top: 20rpx;
}

.address-content {
  flex: 1;
  min-width: 0;
}

.address-header {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
}

.address-name {
  font-size: 30rpx;
  color: #000000;
  margin-right: 20rpx;
}

.address-tel {
  font-size: 30rpx;
  color: #000000;
}

.address-detail {
  font-size: 28rpx;
  color: #999999;
  line-height: 1.5;
  font-weight: 350;
}

.address-actions {
  display: flex;
  align-items: center;
  gap: 30rpx;
  margin-left: 20rpx;
}

.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60rpx;
  height: 60rpx;
}

/* 无数据提示 */
.no-address {
  text-align: center;
  padding: 200rpx 0;
  color: #999;
  font-size: 28rpx;
}

/* 底部新增按钮 */
.add-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background-color: #ff0000;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
  gap: 10rpx;
}

.add-btn-text {
  font-size: 32rpx;
  color: #ffffff;
  font-weight: 500;
}
</style>
